import requests
import json
import os
import datetime
import time
import ntplib
import sys
############################## 康利锋
activityId = "2503090148083191"
inviteUid = 139601259
name = "康利锋"  # 接龙名
itemAttrId = 47954606
yanshi = 1.25
hashcode = "986a99c02921687dfd81e18bc4f5a4fe"
postData = '{"chartOrderDTO":{"orderDefItemList":[{"itemAttrId":47954606,"extensionType":0,"attrInputDTO":{"type":10,"textInputDTO":{"text":"康利锋"}}}],"markInfoJson":{}},"actId":2503090148083191}'
headers = {
    "Host": "apipro.qunjielong.com",
    "Connection": "keep-alive",
    "Device-Type": "10",
    "Mini-Route": "pro/pages/nav/nav",
    "Authorization": "eyJhbGciOiJIUzUxMiJ9.eyJ1aWQiOjE4ODQ3Mjc4OCwiZXhwIjoxNzQyMDk2NzU4fQ.vW6qj2I8zC9eXCg1i_YaNdQdaKO_jjLzGfR4M44fK_0rMdddHQTZNAFsn-D44J9Qr8qpOqZz5XE7_TWLdu6eSw",
    "Uid": "188472788",
    "Companyid": "190",
    "Feature-Tag": "f0000",
    "Qjl-Request-Level": "LV1",
    "Client-Version": "5.8.21",
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36 MicroMessenger/7.0.20.1781(0x6700143B) NetType/WIFI MiniProgramEnv/Windows WindowsWechat/WMPF WindowsWechat(0x63090c2d)XWEB/11581",
    "Content-Type": "application/json",
    "Appid": "wx059cd327295ab444",
    "Scenecode": "1260",
    "Version": "3.0.0",
    "Accept": "*/*",
    "Sec-Fetch-Site": "cross-site",
    "Sec-Fetch-Mode": "cors",
    "Sec-Fetch-Dest": "empty",
    "Referer": "https://servicewechat.com/wx059cd327295ab444/2035/page-frame.html",
    "Accept-Encoding": "gzip, deflate, br",
    "Accept-Language": "zh-CN,zh;q=0.9"
}

headers["hash"] = hashcode

##############################
Authorization = headers.get("Authorization")
logname = os.path.basename(__file__).split('.')[0] + ".log"
if len(sys.argv) > 1:
    yanshi = float(sys.argv[1].strip())
servertime_s = 0
servertime_ms = 0
ntpclient = ntplib.NTPClient()
stime = time.time()
resp = ntpclient.request("ntp.aliyun.com")
etime = time.time()
print(etime, resp.tx_time)
dtime = resp.tx_time - etime + (etime - stime) / 2
if abs(dtime) >= 1:
    servertime_s = dtime // 1
servertime_ms = (dtime % 1) * 1000 // 1
servertime_ms = 0

info_url = "https://apipro.qunjielong.com/activity-biz/activity/detail/frame/chart"
data = {
	"activityId": activityId,
	"enterStatus": 1,
	"inviteUid": inviteUid,
    "fansOriginType": 0
}
proxies = {"http": None, "https": None}
stime = time.time()
res = requests.post(info_url, headers=headers, data=json.dumps(data), proxies=proxies)
dtime_qunjielong = (time.time() - stime) / 2
js = res.json()
stime = datetime.datetime.now()
if js.get("data") and js.get("data").get("activity") and js.get("data").get("activity").get("startTime"):
    stime = datetime.datetime.fromtimestamp(js.get("data").get("activity").get("startTime") / 1000)
    stime -= datetime.timedelta(seconds=1)

print("时差{}.{}".format(int(servertime_s), int(servertime_ms)))
print(stime.strftime("%Y-%m-%d %H:%M:%S"))
print("延时：" + str(yanshi))
dtime_qunjielong = 0.168
print("IO时间:{}ms".format(int(dtime_qunjielong * 1000)))
with open("log.txt", "a") as f_a:
    f_a.write(str(int(dtime_qunjielong * 1000)) + " " + str(yanshi) + " ")
while (datetime.datetime.now() + datetime.timedelta(seconds=servertime_s) + datetime.timedelta(milliseconds=servertime_ms)) < stime:
    pass

time.sleep(yanshi)

def run(f_w):
    try:
        data = {
            "chartOrderDTO": {
                "orderDefItemList": [{
                    # "itemAttrId": js.get("data").get("chartActParticipatorFillContentDTO").get("actItemAttrs")[0].get(
                    #     "itemAttrId"),
                    "itemAttrId": itemAttrId,
                    "extensionType": 0,
                    "attrInputDTO": {
                        "type": 10,
                        "textInputDTO": {
                            "text": name
                        }
                    }
                }],
                "markInfoJson": {}
            },
            "actId": activityId
        }
        print(data)
        f_w.write(json.dumps(data) + "\n")
        place_all = "https://apipro.qunjielong.com/order-place/api/mina/order_place/place-all"
        newheaders = {
            "Host": "apipro.qunjielong.com",
            "device-type": "10",
            "mini-route": "pro/pages/generate-order/generate-order",
            "hash": hashcode,
            "Authorization": headers.get("Authorization"),
            "requestVersion": "2.0.0",
            "uid": headers.get("uid") if headers.get("uid") else headers.get("Uid"),
            "companyId": "190",
            "feature-tag": "f0000",
            "scene-flow": "pro/pages/generate-order/generate-order,4752b3bc27f6b7e0416f1a429bb7b82d",
            "client-version": "5.8.21",
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36 MicroMessenger/7.0.20.1781(0x6700143B) NetType/WIFI MiniProgramEnv/Windows WindowsWechat/WMPF WindowsWechat(0x63090c2d)XWEB/11581",
            "Content-Type": "application/json",
            "xweb_xhr": "1",
            "appid": "wx059cd327295ab444",
            "sceneCode": "1256",
            "version": "3.0.0",
            "Accept": "*/*",
            "Referer": "https://servicewechat.com/wx059cd327295ab444/2035/page-frame.html"
        }
        res = requests.post(place_all, headers=newheaders, data=postData, proxies=proxies)
        print(res.text)
        f_w.write(res.text + "\n")
        js = res.json()
        if js.get("data").get("success"):
            with open("log.txt", "a", encoding="UTF-8") as f_a:
                f_a.write("行\n")
            query_order_personal_home_page = "https://apipro.qunjielong.com/order-cert/api/mina/user-order/query_order_personal_home_page?page=1&pageSize=1"
            res = requests.post(query_order_personal_home_page, data=json.dumps({}), headers=headers, proxies=proxies)
            js = res.json()
            f_w.write(json.dumps(js, indent=4, ensure_ascii=False, sort_keys=True))
            f_w.write("\n")
            print("接龙序号：{}".format(str(js.get("data").get("entityList")[0].get("actNo"))))
            return True
        else:
            with open("log.txt", "a", encoding="UTF-8") as f_a:
                f_a.write("不行\n")
        return False

    except Exception as e:
        print(e)
        with open("log.txt", "a", encoding="UTF-8") as f_a:
            f_a.write("不行\n")
        return False


with open(logname, "w") as f_w:
    for i in range(1):
        f_w.write(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f") + "\n")
        if run(f_w):
            break
        time.sleep(0.2)

